-module(bankserver).
-export([start/0]).

start() ->
	server(3010),
	sleep(infinity).
	
server(Port) ->
	{ok, Listen} = gen_tcp:listen(Port, [binary, {packet, 4}, {reuseaddr, true}, {active, true}]),
	io:fwrite("Listening: ~w~n", [Listen]),
	spawn(fun() -> accept_client(Listen) end).

accept_client(Listener) ->
	{ok, Socket} = gen_tcp:accept(Listener),
	io:format("Socket accepted: ~w~n", [Socket]),
	spawn(fun() -> accept_client(Listener) end),
	handle_client(Socket).	


%{ok, Socket} = gen_tcp:accept(Listen),
%io:fwrite("Accepted Client: ~w~n", [Socket]),
% spawn(fun() -> handle_request(Socket) end).
%handle_request(Socket).
	
handle_client(Socket) ->
	io:fwrite("Handling client: ~w~n", [Socket]),
	
	receive
		{tcp, Socket, Data} ->
			io:format("Received ~p~n", [Data]),
			% return some data
			gen_tcp:send(Socket, <<"123">>),
			handle_client(Socket);			
		{tcp_closed, Socket} ->
			void
			%io:format("Server socket closed~n"),
			%exit(normal)
	end.
	
sleep(T) ->
	receive
		after T ->
			true
	end.